<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Warehouse\Controllers;


use App\Api\Service\Warehouse\Models\OrderWarehouse;
use App\Eloquent\Ygt\Order;
use App\Eloquent\Ygt\Warehouse;
use App\Eloquent\Ygt\WarehouseCart;
use App\Eloquent\Ygt\WarehouseLog;
use App\Eloquent\Ygt\DepartmentUser;
use App\Engine\Func;
use App\Engine\WarehouseEngine;
use Framework\BaseClass\Api\Controller;
use phpDocumentor\Reflection\Types\Null_;

class IndexController extends Controller
{
    public $userId          = 25;
    public function index(){}
    //厂的成品列表
    public function listStock()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $page               = request('page',1);
        $limit              = request('page_num',10);
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $offset             = ($page-1)*$limit;
        $where              = ['company_id'=>$companyId];
        $warehouseList      = Warehouse::getList($where,'',$limit,$offset)->toArray();
        foreach($warehouseList as $key=>$val)
        {
            $createdAt      = $val['created_at'];
            $createdAtYmd   = date('Y-m-d',$createdAt);
            $warehouseList[$key]['created_at_ymd']  = $createdAtYmd;
            $warehouseList[$key]['order_title']  = \App\Engine\Common::changeSnCode($val['order_title']);
        }
        $count              = Warehouse::getCount($where);
        $listData           = [
//            'warehouse_list'=>$warehouseList
        ];
        $pagingData         = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($warehouseList, $pagingData);
    }
    //客户的成品列表
    public function lists()
    {
        $userId             = 25;//Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $page               = request('page',1);
        $limit              = request('page_num',10);
        $customerId         = request('customer_id',0);
        $keyword         = request('keyword','');
        if( !$userInfo || !$customerId )
        {
            xThrow( ERR_PARAMETER );
        }
        $offset             = ($page-1)*$limit;
        $where              = ['customer_id'=>$customerId];

        if(!empty($keyword)){
            $where['product_name'] = ['like',"%".$keyword."%"];
        }

        $where['now_number'] = ['>',0];

        $orderList          = Warehouse::getList($where,'',$limit,$offset);
        $totalBillNumber    = 0;
        foreach($orderList as $key=>$val)
        {
            $totalBillNumber    += $val['bill_number'];
            $orderList[$key]['status_name'] = '需交货';
        }
        $result             = [
            'order_list'=>$orderList,'total_bill_number'=>$totalBillNumber
        ];
        return $result;
    }
    //成品入库
    public function edit()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $orderId            = request('order_id',0);
        $number             = request('number',0);
        if( !$userInfo || !$orderId || !$number)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['id'=>$orderId,'company_id'=>$companyId];
        $orderInfo          = Order::where($where)->first();
        if(!$orderInfo)
        {
            xThrow( ERR_PARAMETER );
        }
        $isSubmit           = request('is_submit',1);
        if($isSubmit){
            $insertResult   = WarehouseEngine::insertOneData($userId,$orderId,$number);
            if($insertResult === false)
            {
                xThrow(ERR_UNKNOWN);
            }
            $result         = ['message'=>'添加成功'];
            return $result;
        } else {
            xThrow(ERR_UNKNOWN);
        }
    }

    //成品生成应收单的前一步
    public function bill()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $customerId         = request('customer_id',0);
        $billArr            = request('bill_arr');
        if($billArr){
            $billArr        = \GuzzleHttp\json_decode(htmlspecialchars_decode($billArr), true);
        }else{
            $billArr        = [];
        }
//        $warehouseIdArr     = request('warehouse_id',[]);
//        $billNumberArr      = request('bill_number',[]);
        if( !$userInfo || !$customerId || empty($billArr) )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $isSubmit           = request('is_submit',1);
        if($isSubmit){
            $warehouseIdArrNew          =[];
            $where                      = ['customer_id'=>$customerId];
            $updateAll                  = ['bill_number'=>0];
            Warehouse::where($where)->update($updateAll);
            foreach($billArr as $key=>$val )
            {
                $warehouseId            = $val['warehouse_id'];
                $billNumber             = $val['bill_number'];
                $where                  = ['id'=>$warehouseId,'customer_id'=>$customerId];
                $warehouse              = Warehouse::getInfo($where);
                if($warehouse){
                    $where              = ['id'=>$warehouseId];
                    $data               = ['bill_number'=>$billNumber];
                    Warehouse::updateOneData($where,$data);
                    $warehouseIdArrNew[]    = $warehouseId;
                }
            }
            if(empty($warehouseIdArrNew))
            {
                xThrow(ERR_UNKNOWN);
            }
            $where              = [
                'ygt_warehouse.customer_id'=>$customerId,
                'ygt_warehouse.bill_number'=>['>',0],
            ];
            $orderList          = Warehouse::getList($where);
            $totalMoney         = 0;
            foreach($orderList as $key=>$val)
            {
                $billMoney      = $val['price']*$val['bill_number'];
                $totalMoney     += $billMoney;
                $orderList[$key]['bill_money']  = $billMoney;
            }

//            $customerName               = \App\Engine\Customer::getNameById($customerId);
            $customerName = $payType = '';
            $tmpCustomerRow = \App\Eloquent\Ygt\Customer::where(['id'=>$customerId])->first();
            if($tmpCustomerRow){
                $customerName = $tmpCustomerRow['customer_name'];
                $payType = $tmpCustomerRow['settlement_method'];
            }

            $result             = [
                'order_list'=>$orderList,
                'total_money'=>$totalMoney,
                'customer_name'=>$customerName,
                'pay_type'=> $payType,
            ];
            return $result;
        } else {
            xThrow(ERR_UNKNOWN);
        }
    }
}